package com.hyhy.hycloud.commons.helper;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;

/**
 * @author lanpengfei
 * @date 2019-03-06
 */
public interface DateFormatHelper {
    String DATE_FORMAT_DAY = "yyyy-MM-dd";
    String DATE_FORMAT_HOUR = "yyyy-MM-dd HH";
    String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
    String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";

    String DATE_FORMAT_DAY_REGEX = "^\\d{4}-\\d{1,2}-\\d{1,2}$";
    String DATE_FORMAT_HOUR_REGEX = "^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}$";
    String DATE_FORMAT_MINUTE_REGEX = "^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}$";
    String DATE_FORMAT_SECOND_REGEX = "^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$";

    String SEPARATOR_SLASH = "/";
    String SEPARATOR_HYPHEN = "-";

    default String init(String source) {
        source = source.trim();
        return source.contains(SEPARATOR_SLASH) ? source.replaceAll(SEPARATOR_SLASH, SEPARATOR_HYPHEN) : source;
    }

    default DateFormat initDateFormat(String source) {
        source = init(source);
        DateFormat df;
        if (source.matches(DATE_FORMAT_DAY_REGEX)) {
            df = new SimpleDateFormat(DATE_FORMAT_DAY);
        } else if (source.matches(DATE_FORMAT_HOUR_REGEX)) {
            df = new SimpleDateFormat(DATE_FORMAT_HOUR);
        } else if (source.matches(DATE_FORMAT_MINUTE_REGEX)) {
            df = new SimpleDateFormat(DATE_FORMAT_MINUTE);
        } else if (source.matches(DATE_FORMAT_SECOND_REGEX)) {
            df = new SimpleDateFormat(DATE_FORMAT_SECOND);
        } else {
            df = null;
        }
        return df;
    }

    default DateTimeFormatter initDateTimeFormatter(String source) {
        source = init(source);
        DateTimeFormatter dtf;
        if (source.matches(DATE_FORMAT_DAY_REGEX)) {
            dtf = DateTimeFormatter.ofPattern(DATE_FORMAT_DAY);
        } else if (source.matches(DATE_FORMAT_HOUR_REGEX)) {
            dtf = DateTimeFormatter.ofPattern(DATE_FORMAT_HOUR);
        } else if (source.matches(DATE_FORMAT_MINUTE_REGEX)) {
            dtf = DateTimeFormatter.ofPattern(DATE_FORMAT_MINUTE);
        } else if (source.matches(DATE_FORMAT_SECOND_REGEX)) {
            dtf = DateTimeFormatter.ofPattern(DATE_FORMAT_SECOND);
        } else {
            dtf = null;
        }
        return dtf;
    }
}
